package org.epidroid.epidroid.news.ui;

import java.util.ArrayList;

import org.apache.james.mime4j.codec.DecoderUtil;
import org.epidroid.epidroid.R;
import org.epidroid.epidroid.news.engine.Topic;

import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;

public class ListTopicsAdapter extends ArrayAdapter<Topic> {

	private ArrayList<Topic> _items = null;
	private ListTopicsActivity _context = null;

	public ListTopicsAdapter(ListTopicsActivity context,
			int textViewResourceId, ArrayList<Topic> objects) {
		super(context, textViewResourceId, objects);

		_items = objects;
		_context = context;
	}
	
	public void setItems (ArrayList<Topic> topics) {
		_items = topics;
	}

	@Override
	public int getCount() {
		Log.d("News", "getCount="+_items.size());
		return _items.size();
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		Log.d("News", "getView on position:" + position);
		View v = convertView;
		ViewHolder holder;
		
		if (v == null) {
			holder = new ViewHolder();
			LayoutInflater inflater = (LayoutInflater) _context
					.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			v = inflater.inflate(R.layout.news_group_item, null);
			holder.title = (TextView) v.findViewById(R.id.news_group_item_title);
			holder.item_desc = (TextView) v.findViewById(R.id.news_group_item_desc);
			holder.item_nb = (TextView) v.findViewById(R.id.news_group_item_nb);
			v.setTag(holder);
		}
		else {
			holder = (ViewHolder) convertView.getTag();
		}

		final Topic t = this._items.get(position);

		v.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				_context.showTopic(t.getServId());
			}
		});

		setTitle(t, holder.title);

		// Get author
		if (t.getNbArticles() > 0) {
			holder.item_desc.setText(DecoderUtil.decodeEncodedWords(t.getArticleByIndex(0)
					.getFrom(), null));
		}

		int nb = t.getNbArticles();
		if (nb < 2)
			holder.item_nb.setText(nb + " message");
		else
			holder.item_nb.setText(nb + " messages");

		return (v);
	}

	private void setTitle(Topic t, TextView view) {
		//final NewsArticle m = t.getArticleByIndex(0);
		String title = t.getSubject();
//		try {
//			title = DecoderUtil.decodeEncodedWords(m.getSubject(), null);
//		} catch (Exception e) {
//			Log.v(NewsActivity.LOGCAT, e.getMessage());
//			title = m.getSubject();
//		}
		view.setText(title);
	}
	
	private class ViewHolder {
		TextView title;
		TextView item_desc;
		TextView item_nb;
	}
}
